<template>
    <el-dialog :visible.sync="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false"
               :close-on-press-escape="false">
        <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="120px">
            <el-form-item prop="title" label="标题">
                <el-input v-model="dataForm.title" placeholder="标题"></el-input>
            </el-form-item>
            <el-form-item prop="content" label="内容">
                <!-- 富文本编辑器, 容器 -->
                <div id="J_quillEditor"></div>
                <!-- 自定义上传图片功能 (使用element upload组件) -->
                <el-upload :action="uploadUrl" :show-file-list="false" :before-upload="uploadBeforeUploadHandle"
                           :on-success="uploadSuccessHandle" style="display: none;">
                    <el-button ref="uploadBtn" type="primary" size="small">上传</el-button>
                </el-upload>
            </el-form-item>
            <el-form-item label="类型" prop="type">
                <el-select v-model="dataForm.typeCode" filterable placeholder="类型" clearable>
                    <el-option v-for="item in typeList" :key="item.code" :value="item.code"
                               :label="item.type"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="deptName" label="所属部门" class="dept-list">
                <el-popover v-model="deptListVisible" ref="deptListPopover" placement="bottom-start" trigger="click">
                    <el-tree
                            :data="deptList"
                            :props="{ label: 'name', children: 'children' }"
                            node-key="id"
                            ref="deptListTree"
                            :highlight-current="true"
                            :expand-on-click-node="false"
                            accordion
                            @current-change="deptListTreeCurrentChangeHandle">
                    </el-tree>
                </el-popover>
                <el-input v-model="dataForm.deptName" v-popover:deptListPopover :readonly="true"
                          :placeholder="$t('user.deptName')"></el-input>
            </el-form-item>
            <el-form-item prop="pubDate" label="发布日期">
                <el-date-picker v-model="dataForm.pubDate" type="datetime" value-format="timestamp"
                                placeholder="发布日期"></el-date-picker>
            </el-form-item>
        </el-form>
        <template slot="footer">
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
        </template>
    </el-dialog>
</template>

<script>
  import debounce from 'lodash/debounce'
  import 'quill/dist/quill.snow.css'
  import Quill from 'quill'

  export default {
    data () {
      return {
        visible: false,
        deptList: [],
        typeList: [],
        deptListVisible: false,
        quillEditor: null,
        quillEditorToolbarOptions: [
          ['bold', 'italic', 'underline', 'strike'],
          ['blockquote', 'code-block', 'image'],
          [{ 'header': 1 }, { 'header': 2 }],
          [{ 'list': 'ordered' }, { 'list': 'bullet' }],
          [{ 'script': 'sub' }, { 'script': 'super' }],
          [{ 'indent': '-1' }, { 'indent': '+1' }],
          [{ 'direction': 'rtl' }],
          [{ 'size': ['small', false, 'large', 'huge'] }],
          [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
          [{ 'color': [] }, { 'background': [] }],
          [{ 'font': [] }],
          [{ 'align': [] }],
          ['clean']
        ],
        uploadUrl: '',
        dataForm: {
          id: '',
          title: '',
          content: '',
          deptId: '',
          deptName: '',
          typeCode: '',
          typeName: '',
          pubDate: ''
        }
      }
    },
    computed: {
      dataRule () {
        let validateContent = (rule, value, callback) => {
          if (this.quillEditor.getLength() <= 1) {
            return callback(new Error(this.$t('validate.required')))
          }
          callback()
        }
        return {
          title: [
            { required: true, message: this.$t('validate.required'), trigger: 'blur' }
          ],
          content: [
            { required: true, message: this.$t('validate.required'), trigger: 'blur' },
            { validator: validateContent, trigger: 'blur' }
          ],
          pubDate: [
            { required: true, message: this.$t('validate.required'), trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      init () {
        this.visible = true
        this.$nextTick(() => {
          if (this.quillEditor) {
            this.quillEditor.deleteText(0, this.quillEditor.getLength())
          } else {
            this.quillEditorHandle()
          }
          this.$refs['dataForm'].resetFields()
          Promise.all([
            this.queryTypes(),
            this.getDeptList(),
            this.getInfo()
          ]).then(() => {
              this.getInfo()
          })
        })
      },
      // 富文本编辑器
      quillEditorHandle () {
        this.quillEditor = new Quill('#J_quillEditor', {
          modules: {
            toolbar: this.quillEditorToolbarOptions
          },
          theme: 'snow'
        })
        // 自定义上传图片功能 (使用element upload组件)
        this.uploadUrl = `${window.SITE_CONFIG['apiURL']}/sys/oss/upload?token=${sessionStorage.getItem('token')}`
        this.quillEditor.getModule('toolbar').addHandler('image', () => {
          this.$refs.uploadBtn.$el.click()
        })
        // 监听内容变化，动态赋值
        this.quillEditor.on('text-change', () => {
          this.dataForm.content = this.quillEditor.root.innerHTML
        })
      },
      // 上传图片之前
      uploadBeforeUploadHandle (file) {
        if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
          this.$message.error('只支持jpg、png、gif格式的图片！')
          return false
        }
      },
      // 上传图片成功
      uploadSuccessHandle (res, file, fileList) {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.quillEditor.insertEmbed(this.quillEditor.getSelection().index, 'image', res.data.src)
      },
      // 获取信息
      getInfo () {
        if(this.dataForm.id != undefined){
          this.$http.get(`/business/question/${this.dataForm.id}`).then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            this.dataForm = res.data
            this.quillEditor.root.innerHTML = this.dataForm.content
          }).catch(() => {
          })
        }
        
      },
      // 表单提交
      dataFormSubmitHandle: debounce(function () {
        this.$refs['dataForm'].validate((valid) => {
          if (!valid) {
            return false
          }
          for (let i = 0; i < this.typeList.length; i++) {
            let type = this.typeList[i]
            if (this.dataForm.typeCode == type.code) {
              this.dataForm.typeName = type.type
            }
          }

          this.$http[!this.dataForm.id ? 'post' : 'put']('/business/question', this.dataForm).then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            this.$message({
              message: this.$t('prompt.success'),
              type: 'success',
              duration: 500,
              onClose: () => {
                this.visible = false
                this.$emit('refreshDataList')
              }
            })
          }).catch(() => {
          })
        })
      }, 1000, { 'leading': true, 'trailing': false }),
      // 获取部门列表
      getDeptList () {
        return this.$http.get('/sys/dept/list').then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.deptList = res.data
        }).catch(() => {
        })
      },

      // 所属部门树, 选中
      deptListTreeCurrentChangeHandle (data, node) {
        this.dataForm.deptId = data.id
        this.dataForm.deptName = data.name
        this.deptListVisible = false
      },

      // 类型列表
      queryTypes () {
        this.$http.get('/business/type/list')
          .then(({ data: res }) => {
            if (res.code == 0) {
              this.typeList = res.data
            } else {
              this.$message.error(res.msg)
            }
          })
          .catch(() => {
          })
      }
    }
  }
</script>
